﻿namespace YnabCsvConverter
{
   using System;
   using System.IO;
   using System.Linq;
   using System.Reflection;
   using System.Windows;

   /// <summary>
   /// Interaction logic for App.xaml
   /// </summary>
   public partial class App : Application
   {
      /// <summary>
      /// Initializes a new instance of the <see cref="App" /> class.
      /// </summary>
      public App()
      {
         AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ResolveAssembly);
      }

      /// <summary>
      /// Resolves the assembly.
      /// </summary>
      /// <param name="sender">The sender.</param>
      /// <param name="args">The <see cref="ResolveEventArgs" /> instance containing the event data.</param>
      /// <returns></returns>
      static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
      {
         Assembly embeddedAssembly = null;

         Assembly thisAssembly = Assembly.GetExecutingAssembly();

         // Get the Name of the AssemblyFile
         var name = args.Name.Substring(0, args.Name.IndexOf(',')) + ".dll";

         //Load form Embedded Resources - This Function is not called if the Assembly is in the Application Folder
         var resources = thisAssembly.GetManifestResourceNames().Where(s => s.EndsWith(name)).ToList();
         if (resources.Any())
         {
            var resourceName = resources.First();
            
            using (Stream stream = thisAssembly.GetManifestResourceStream(resourceName))
            {
               if (stream != null)
               {
                  var block = new byte[stream.Length];
                  stream.Read(block, 0, block.Length);
                  
                  embeddedAssembly = Assembly.Load(block);
               }
            }
         }

         return embeddedAssembly;
      }
   }
}
